package com.aorise.controller.approve;

import com.aorise.model.approve.ApproveModel;
import com.aorise.model.halt.HaltModel;
import com.aorise.model.migration.MigrationModel;
import com.aorise.service.approve.ApproveService;
import com.aorise.service.halt.HaltService;
import com.aorise.service.migration.MigrationService;
import com.aorise.utils.ConstDefine;
import com.aorise.utils.StatusDefine;
import com.aorise.utils.StatusDefineMessage;
import com.aorise.utils.json.JsonResponseData;
import com.aorise.utils.page.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Author:cat
 * @Desicription: 计划停机控制器类
 * @Date:Created in 2019-06-17
 * @Modified By:
 */
@RestController
@Api(description ="审批中心接口")
public class ApproveController {

    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private ApproveService approveService;
    @Autowired
    private HaltService haltService;
    @Autowired
    private MigrationService migrationService;

    /**
     * 根据筛选条件进行分页查询审批信息
     * HTTP 方式：GET
     * API 路径：/api/approve/pageIndex/{pageIndex}/pageNum/{pageNum}
     * 方法名：getAllApproveListByPage
     * 方法返回类型：String
     *
     * @Author: cat
     * @Date: 2019-06-11
     */
    @ApiOperation(value = "根据筛选条件进行分页查询审批信息", httpMethod = "GET", response = String.class, notes = "根据筛选条件进行分页查询审批信息,提供审批中心-查询列表使用")
    @RequestMapping(value = "/api/approve/pageIndex/{pageIndex}/pageNum/{pageNum}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public String getAllApproveListByPage(@ApiParam(value = "起始申请日期", required = false) @RequestParam(value = "startCreateTime", required = false) String startCreateTime,
                                         @ApiParam(value = "截止申请日期", required = false) @RequestParam(value = "endCreateTime", required = false) String endCreateTime,
                                         @ApiParam(value = "审批类型：1计划停机,2点位迁建", required = false) @RequestParam(value = "type", required = false) Integer type,
                                         @ApiParam(value = "审批状态：1待审批，2通过，3驳回", required = false) @RequestParam(value = "status", required = false) Integer status,
                                         @ApiParam(value = "页索引", required = true) @PathVariable(value = "pageIndex", required = true) String pageIndex,
                                         @ApiParam(value = "页大小", required = true) @PathVariable(value = "pageNum", required = true) String pageNum) {
        logger.debug("Request RESTful API:getAllApproveListByPage");
        logger.debug("startCreateTime：" + startCreateTime);
        logger.debug("endCreateTime：" + endCreateTime);
        logger.debug("type：" + type);
        logger.debug("status：" + status);
        logger.debug("pageIndex" + pageIndex);
        logger.debug("pageNum" + pageNum);

        Page page = new Page();
        if (!StringUtils.isBlank(pageIndex)) {
            page.setCurrentPage(Long.parseLong(pageIndex.toString()));
        }
        if (!StringUtils.isBlank(pageNum)) {
            page.setEveryPage(Long.parseLong(pageNum.toString()));
        }
        try {

            Map<String, Object> map = new HashMap<>();
            map.put("startCreateTime", startCreateTime);
            map.put("endCreateTime", endCreateTime);
            map.put("type", type);
            map.put("status", status);
            map.put("typeHalt", ConstDefine.APPROVE_TYPE_HALT);
            map.put("typeMigration", ConstDefine.APPROVE_TYPE_MIGRATION);
            map.put("state", ConstDefine.STATE_ABLE);
            map.put("beginIndex", page.getBeginIndex());
            map.put("endinIndex", page.getEndinIndex());

            List<ApproveModel> approveModels = approveService.getAllApproveListByPage(map, page);
            page.setList(approveModels);

            return new JsonResponseData(true,
                    StatusDefineMessage.GetMessage(StatusDefine.SUCCESS), StatusDefine.SUCCESS, "", page).toString();
        } catch (DataAccessException e) {
            logger.error(
                    "controller:ApproveController. function:getAllApproveListByPage...msg:Get Approve List By Page DataAccessException. error:"
                            + e.getMessage());
            logger.error("error:" + e.getMessage());
            return new JsonResponseData(false, "", StatusDefine.DB_ERROR,
                    StatusDefineMessage.GetMessage(StatusDefine.DB_ERROR), page).toString();
        } catch (Exception e) {
            logger.error(
                    "controller:ApproveController. function:getAllApproveListByPage...msg:Get Approve List By Page Exception. error:"
                            + e.getMessage());
            logger.error("error:" + e.getMessage());
            return new JsonResponseData(false, "", StatusDefine.SYS_ERROR,
                    StatusDefineMessage.GetMessage(StatusDefine.SYS_ERROR), page).toString();
        }
    }

    /**
     * 根据ID查询审批详情
     * HTTP 方式：GET
     * API 路径：/api/approve/id/{id}
     * 方法名：getApproveById
     * 方法返回类型：String
     *
     * @Author: cat
     * @Date: 2019-06-18
     */
    @ApiOperation(value = "根据ID查询审批详情", httpMethod = "GET", response = String.class, notes = "根据ID查询审批详情，提供审批中心-查询审批记录详情使用")
    @RequestMapping(value = "/api/approve/id/{id}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public String getApproveById(@ApiParam(value = "ID", required = true) @PathVariable(value = "id", required = true) Integer id,
                              @ApiParam(value = "审批类型：1计划停机,2点位迁建", required = true) @RequestParam(value = "type", required = true) Integer type,
                                 @ApiParam(value = "登录人ID", required = true) @RequestParam(value = "userId", required = true) Integer userId) {

        logger.debug("Request RESTful API:getApproveById");
        logger.debug("id" + id);
        logger.debug("type" + type);
        logger.debug("userId" + userId);
        try {
            if(type==ConstDefine.APPROVE_TYPE_HALT){
                HaltModel haltModel = haltService.getHaltById(id, userId);
                return new JsonResponseData(true,
                        StatusDefineMessage.GetMessage(StatusDefine.SUCCESS), StatusDefine.SUCCESS, "", haltModel).toString();
            }else {
                MigrationModel migrationModel = migrationService.getMigrationById(id,userId);
                return new JsonResponseData(true,
                        StatusDefineMessage.GetMessage(StatusDefine.SUCCESS), StatusDefine.SUCCESS, "",migrationModel).toString();
            }
        } catch (DataAccessException e) {
            logger.error(
                    "controller:ApproveController. function:getApproveById...msg:Get Approve By Id DataAccessException. error:"
                            + e.getMessage());
            logger.error("error:" + e.getMessage());
            return new JsonResponseData(false, "", StatusDefine.DB_ERROR,
                    StatusDefineMessage.GetMessage(StatusDefine.DB_ERROR), null).toString();
        } catch (Exception e) {
            logger.error(
                    "controller:ApproveController. function:getApproveById...msg:Get Approve By Id Exception. error:"
                            + e.getMessage());
            logger.error("error:" + e.getMessage());
            return new JsonResponseData(false, "", StatusDefine.SYS_ERROR,
                    StatusDefineMessage.GetMessage(StatusDefine.SYS_ERROR), null).toString();
        }
    }

    /**
     * 审批计划停机、点位迁建申请
     * HTTP 方式：POST
     * API 路径：/api/approve/approveHaltMigration
     * 方法名：approveHaltMigration
     * 方法返回类型：String
     *
     * @Author: cat
     * @Date: 2019-06-11
     */
    @ApiOperation(value = "审批计划停机、点位迁建申请", httpMethod = "POST", response = String.class, notes = "审批计划停机、点位迁建申请，提供审批中心-审批申请使用")
    @RequestMapping(value = "/api/approve/approveHaltMigration", method = RequestMethod.POST, produces = "application/json")
    public String approveHaltMigration(@ApiParam(value = "ID", required = true) @RequestParam(value = "id", required = true) Integer id,
                                       @ApiParam(value = "审批类型：1计划停机,2点位迁建", required = true) @RequestParam(value = "type", required = true) Integer type,
                                       @ApiParam(value = "审批人ID", required = true) @RequestParam(value = "approver", required = true) Integer approver,
                                       @ApiParam(value = "审批状态：1待审批，2通过，3驳回", required = true) @RequestParam(value = "status", required = true) Integer status,
                                       @ApiParam(value = "审批意见", required = true) @RequestParam(value = "message", required = true) String message,
                                       @ApiParam(value = "申请人ID", required = true) @RequestParam(value = "createUser", required = true) Integer createUser,
                                       @ApiParam(value = "记录更新时间", required = true) @RequestParam(value = "editTime", required = true) String editTime) {
        logger.debug("Request RESTful API:approveHaltMigration");
        logger.debug("id" + id);
        logger.debug("type" + type);
        logger.debug("approver" + approver);
        logger.debug("status" + status);
        logger.debug("message" + message);
        logger.debug("createUser" + createUser);
        logger.debug("editTime" + editTime);

        try {
            Map<String, Object> map = new HashMap<>();
            map.put("id", id);
            map.put("type", type);
            map.put("approver", approver);
            map.put("status", status);
            map.put("message", message);
            map.put("createUser", createUser);
            map.put("editUser", approver);
            map.put("state", ConstDefine.STATE_ABLE);
            map.put("editTime", editTime);

            int ret = approveService.approveHaltMigration(map);

            if (ret > 0) {
                return new JsonResponseData(true,
                        StatusDefineMessage.GetMessage(StatusDefine.SUCCESS), StatusDefine.SUCCESS, "", "").toString();
            } else {
                if(type== ConstDefine.APPROVE_TYPE_HALT){
                    return new JsonResponseData(false,
                            "", StatusDefine.FAILURE, StatusDefineMessage.GetMessage(StatusDefine.APPROVE_HALT_EXIST), "").toString();
                }else if(type == ConstDefine.APPROVE_TYPE_MIGRATION){
                    return new JsonResponseData(false,
                            "", StatusDefine.FAILURE, StatusDefineMessage.GetMessage(StatusDefine.APPROVE_MIGRATION_EXIST), "").toString();
                }else {
                    return new JsonResponseData(false,
                            "", StatusDefine.FAILURE, StatusDefineMessage.GetMessage(StatusDefine.APPROVE_EXIST), "").toString();
                }
            }
        } catch (DataAccessException e) {
            logger.error(
                    "controller:ApproveController. function:approveHaltMigration...msg:Approve Halt Migration DataAccessException. error:"
                            + e.getMessage());
            logger.error("error:" + e.getMessage());
            return new JsonResponseData(false, "", StatusDefine.DB_ERROR,
                    StatusDefineMessage.GetMessage(StatusDefine.DB_ERROR), null).toString();
        } catch (Exception e) {
            logger.error(
                    "controller:ApproveController. function:approveHaltMigration...msg:Approve Halt Migration Exception. error:"
                            + e.getMessage());
            logger.error("error:" + e.getMessage());
            return new JsonResponseData(false, "", StatusDefine.SYS_ERROR,
                    StatusDefineMessage.GetMessage(StatusDefine.SYS_ERROR), null).toString();
        }
    }

    /**
     * 查询审批中心待审批消息总数
     * HTTP 方式：GET
     * API 路径：/api/approve/getApproveMsgNum
     * 方法名：getApproveMsgNum
     * 方法返回类型：String
     *
     * @Author: cat
     * @Date: 2019-06-19
     */
    @ApiOperation(value = "查询审批中心待审批消息总数", httpMethod = "GET", response = String.class, notes = "查询审批中心待审批消息总数，提供导航上审批中心查询提醒数使用")
    @RequestMapping(value = "/api/approve/getApproveMsgNum", method = RequestMethod.GET, produces = "application/json")
    public String getApproveMsgNum() {
        logger.debug("Request RESTful API:getApproveMsgNum");

        try {
            Long ret = approveService.getApproveMsgNum();
            return new JsonResponseData(true,
                    StatusDefineMessage.GetMessage(StatusDefine.SUCCESS), StatusDefine.SUCCESS, "", ret).toString();
        } catch (DataAccessException e) {
            logger.error(
                    "controller:ApproveController. function:getApproveMsgNum...msg:Get Approve Message Num DataAccessException. error:"
                            + e.getMessage());
            logger.error("error:" + e.getMessage());
            return new JsonResponseData(false, "", StatusDefine.DB_ERROR,
                    StatusDefineMessage.GetMessage(StatusDefine.DB_ERROR), null).toString();
        } catch (Exception e) {
            logger.error(
                    "controller:ApproveController. function:getApproveMsgNum...msg:Get Approve Message Num Exception. error:"
                            + e.getMessage());
            logger.error("error:" + e.getMessage());
            return new JsonResponseData(false, "", StatusDefine.SYS_ERROR,
                    StatusDefineMessage.GetMessage(StatusDefine.SYS_ERROR), null).toString();
        }
    }

}
